package com.example.service;

import com.example.enums.ReleaseState;
import com.example.mq.GrayMQPushConsumerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;

/**
 * mq灰度注册
 */
@Service
public class GrayMQConsumerRegister {

    private static final Logger logger = LoggerFactory.getLogger(GrayMQConsumerRegister.class);

    @Autowired
    private ServiceAwareReleaseStateService releaseStateService;

    private String env = "prd"; // todo 实际不写死，需传入

    private String appName;

    private boolean hasShutDowned;

    // 应用启动的时候，调此方法注册即可
    public void addApp(String name) {
        this.appName = name;
        // 注册状态变化监听器
        releaseStateService.addServiceStateChangeListener(appName, this::onReleaseStateChanged);
    }

    /**
     * 处理发布状态变化
     */
    private void onReleaseStateChanged(ReleaseState newState) {
        if (env.startsWith("prd") || env.equalsIgnoreCase("prd")) {
            switch (newState) {
                case GRAY_ACCESSABLE:
                    GrayMQPushConsumerFactory.shutDownAll();
                    logger.info("==>> switch to gray, shut down all mq consumers");
                    hasShutDowned = true;
                    break;
                case PROD_ACCESSABLE:
                case ALL_ACCESSABLE:
                    if (hasShutDowned) {
                        // start
                        hasShutDowned = false;
                    }
                    break;
            }
        } else {
            switch (newState) {
                case PROD_ACCESSABLE:
                    GrayMQPushConsumerFactory.shutDownAll();
                    logger.info("==>> switch to prd, shut down all mq consumers");
                    hasShutDowned = true;
                    break;
                case GRAY_ACCESSABLE:
                case ALL_ACCESSABLE:
                    if (hasShutDowned) {
                        // start
                        hasShutDowned = false;
                    }
                    break;
            }
        }
    }

    @PreDestroy
    public void destroy() {
        // 移除监听器
        releaseStateService.removeServiceStateChangeListener(appName, this::onReleaseStateChanged);
    }

}